from datetime import datetime

from fastapi import APIRouter, Depends, Form, Request
from fastapi import File, UploadFile
from pydantic_validation_decorator import ValidateFields
from sqlalchemy.ext.asyncio import AsyncSession

from config.enums import BusinessType
from config.get_db import get_db
from module_admin.annotation.log_annotation import Log
from module_admin.aspect.interface_auth import CheckUserInterfaceAuth
from module_admin.entity.vo.user_vo import CurrentUserModel
from module_admin.service.login_service import LoginService
from module_rag.entity.vo.doc_vo import DeleteDocModel, DocModel, DocPageQueryModel
from module_rag.service.doc_service import DocService
from utils.common_util import bytes2file_response
from utils.log_util import logger
from utils.minio_util import upload_file_to_minio,download_file_from_minio
from utils.page_util import PageResponseModel
from utils.response_util import ResponseUtil

from utils.ai_util import import_chromadb

docController = APIRouter(prefix='/manage/doc', dependencies=[Depends(LoginService.get_current_user)])



@docController.get(
    '/list', response_model=PageResponseModel, dependencies=[Depends(CheckUserInterfaceAuth('manage:doc:list'))]
)
async def get_manage_doc_list(
    request: Request,
doc_page_query: DocPageQueryModel = Depends(DocPageQueryModel.as_query),
    query_db: AsyncSession = Depends(get_db),
):
    # 获取分页数据
    doc_page_query_result = await DocService.get_doc_list_services(query_db, doc_page_query, is_page=True)
    logger.info('获取成功')

    return ResponseUtil.success(model_content=doc_page_query_result)

@docController.post('/upload')
async def upload_file(file: UploadFile  = File(...)):
    # 上传文件到 MinIO
    result = upload_file_to_minio(file)
    return ResponseUtil.success(data=result)

@docController.get('/solve/{doc_id}')
async def solve_doc(request: Request,doc_id: int,query_db: AsyncSession = Depends(get_db)):
    
    doc_detail_result = await DocService.doc_detail_services(query_db=query_db,doc_id=doc_id)

    res = import_chromadb(doc_detail_result.rag_id,doc_detail_result.file_name)
    if(len(res)>0):
        return ResponseUtil.success(data = res )
    else:
        return ResponseUtil.success(data = "导入失败")
@docController.get('/updateDocStatus/{doc_id}/{status}')
async def update_doc_status(request: Request,
                            doc_id: int,
                            status: str,
                            query_db: AsyncSession = Depends(get_db),
                            current_user: CurrentUserModel = Depends(LoginService.get_current_user),):
    edit_doc = await DocService.doc_detail_services(query_db=query_db,doc_id=doc_id)
    edit_doc.status = status
    # edit_doc.update_by = current_user.user.user_name
    # edit_doc.update_time = datetime.now()
    edit_doc_result = await DocService.edit_doc_services(query_db, edit_doc)
    logger.info(edit_doc_result.message)

    return ResponseUtil.success(msg=edit_doc_result.message)


@docController.post('', dependencies=[Depends(CheckUserInterfaceAuth('manage:doc:add'))])
@ValidateFields(validate_model='add_doc')
@Log(title='知识库附属文档信息', business_type=BusinessType.INSERT)
async def add_manage_doc(
    request: Request,
    add_doc: DocModel,
    query_db: AsyncSession = Depends(get_db),
    current_user: CurrentUserModel = Depends(LoginService.get_current_user),
):
    add_doc_result = await DocService.add_doc_services(query_db, add_doc)
    logger.info(add_doc_result.message)

    return ResponseUtil.success(msg=add_doc_result.message)


@docController.put('', dependencies=[Depends(CheckUserInterfaceAuth('manage:doc:edit'))])
@ValidateFields(validate_model='edit_doc')
@Log(title='知识库附属文档信息', business_type=BusinessType.UPDATE)
async def edit_manage_doc(
    request: Request,
    edit_doc: DocModel,
    query_db: AsyncSession = Depends(get_db),
    current_user: CurrentUserModel = Depends(LoginService.get_current_user),
):
    edit_doc_result = await DocService.edit_doc_services(query_db, edit_doc)
    logger.info(edit_doc_result.message)

    return ResponseUtil.success(msg=edit_doc_result.message)


@docController.delete('/{doc_ids}', dependencies=[Depends(CheckUserInterfaceAuth('manage:doc:remove'))])
@Log(title='知识库附属文档信息', business_type=BusinessType.DELETE)
async def delete_manage_doc(request: Request, doc_ids: str, query_db: AsyncSession = Depends(get_db)):
    delete_doc = DeleteDocModel(docIds=doc_ids)
    delete_doc_result = await DocService.delete_doc_services(query_db, delete_doc)
    logger.info(delete_doc_result.message)

    return ResponseUtil.success(msg=delete_doc_result.message)


@docController.get(
    '/{doc_id}', response_model=DocModel, dependencies=[Depends(CheckUserInterfaceAuth('manage:doc:query'))]
)
async def query_detail_manage_doc(request: Request, doc_id: int, query_db: AsyncSession = Depends(get_db)):
    doc_detail_result = await DocService.doc_detail_services(query_db, doc_id)
    logger.info(f'获取doc_id为{doc_id}的信息成功')

    return ResponseUtil.success(data=doc_detail_result)


@docController.post('/export', dependencies=[Depends(CheckUserInterfaceAuth('manage:doc:export'))])
@Log(title='知识库附属文档信息', business_type=BusinessType.EXPORT)
async def export_manage_doc_list(
    request: Request,
    doc_page_query: DocPageQueryModel = Form(),
    query_db: AsyncSession = Depends(get_db),
):
    # 获取全量数据
    doc_query_result = await DocService.get_doc_list_services(query_db, doc_page_query, is_page=False)
    doc_export_result = await DocService.export_doc_list_services(request, doc_query_result)
    logger.info('导出成功')

    return ResponseUtil.streaming(data=bytes2file_response(doc_export_result))
